package com.hxzy.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.hxzy.dao.BaseDao.Params;
import com.hxzy.dao.TeamDao;
import com.hxzy.dao.TeamUserDao;
import com.hxzy.dao.UserDao;
import com.hxzy.entity.Team;
import com.hxzy.entity.TeamUser;
import com.hxzy.entity.User;
import com.hxzy.tms.SessionHolder;

public class TeamServiceImpl implements TeamService {

    private TeamDao teamDao;
    private UserDao userDao;
    private TeamUserDao teamUserDao;

    public boolean findTeamName(String name, String subdomain) {
        // TODO Auto-generated method stub
        // Session session=HibernateSessionHolder.get();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("name", name);
        param.put("subdomain", subdomain);
        List<Team> teamList = teamDao.read("from Team where name =:name or subdomain =:subdomain", param);
        boolean isTeamNameExists = false;
        while (teamList.size() == 1) {
            isTeamNameExists = true;
            break;
        }
        return isTeamNameExists;
    }
    //index team list
    public List<Team> list(Integer status) {
        // TODO Auto-generated method stub
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("status", status);
        List<Team> teamList = teamDao.read("from Team where status = :status", param);
        return teamList;
    }
    /**
     * invite team member
     */
    public int invite(long uid, long teamId, String email) {
        if (uid <= 0) {
            throw new RuntimeException("uid less than or equal 0");
        }
        if (StringUtils.isBlank(email)) {
            throw new RuntimeException("email is empty");
        }
        if (teamId <= 0) {
            throw new RuntimeException("teamId less than or equal 0");
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("email", email);
        List<User> invitedUsers = userDao.read("from User where email =:email", param);
        if (invitedUsers.isEmpty()) {
            return -1;// email and user is not exists
        }
        User invitedUser = invitedUsers.get(0);
        Team team = teamDao.read(Team.class, teamId);
        if (team.getUidCreate().getId() != uid) {
            return -2;// uid not create this team
        }
        Map<String, Object> param2 = new HashMap<String, Object>();
        param2.put("userId", invitedUser.getId());
        param2.put("teamId", team.getId());
        List<TeamUser> teamUser = teamUserDao.read("from TeamUser where user.id =:userId and team.id =:teamId", param2);
        if (!teamUser.isEmpty()) {
            return -3;// this user is already exists
        }
        TeamUser teamUser2 = new TeamUser();
        teamUser2.setUser(invitedUser);
        teamUser2.setTeam(team);
        teamUser2.setGmtCreate(System.currentTimeMillis() / 1000);
        teamUser2.setStatus(1);
        teamUser2.setUidCreate(uid);
        teamUser2.setUserNickname(invitedUser.getNickname());
        teamUserDao.create(teamUser2);
        return 1;
    }

    public List<Team> myTeam(Long uidCreate) {
        // TODO Auto-generated method stub
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("uidCreate", uidCreate);
        List<Team> myTeamList = teamDao.read("from Team where uidCreate = :uidCreate", param);
        return myTeamList;
    }
    //create team
    public ServiceResult<Team> create(String name, String desc, String subdomain,String intro,  Date gmtBegin,
            Date gmtEnd) {
        // TODO Auto-generated method stub
        return saveOrUpdate(null, name, desc, intro, subdomain, gmtBegin, gmtEnd);
    }
    
    public ServiceResult<Team> update(long id, String name, String desc, String intro, String subdomain, Date gmtBegin,
            Date gmtEnd) {
        // TODO Auto-generated method stub
        return saveOrUpdate(id,name,desc,intro,subdomain,gmtBegin,gmtEnd);
    }
    
    public ServiceResult<Team> saveOrUpdate(Long id, String name, String desc, String intro, String subdomain, Date gmtBegin,
            Date gmtEnd){
//        if(gmtBegin.getTime()<=gmtEnd.getTime()){
//            return new ServiceResult<Team>(-1,null,"begin time need more than end time");
//        }
        if(id!=null&&teamDao.read(Team.class, id)!=null
                && teamDao.read(Team.class, id).getUidCreate().getId() != SessionHolder.get().getId()){
            return new ServiceResult<Team>(-2,null,"can't modified the not owner team");
        }
        List<Team> teamList=new ArrayList<Team>();
        if(id!=null){
            teamList=teamDao.read("from Team where name= :name and id!= :id", new Params("name",name),new Params("id",id));
        }else{
            teamList=teamDao.read("from Team where name= :name", new Params("name",name));
        }
        if(teamList!=null){
            return new ServiceResult<Team>(-3,null,"the name is repeat");
        }
        if(id!=null){
            teamList=teamDao.read("from Team where subdomain=:subdomain and id!=:id", new Params("subdomain",subdomain),new Params("id",id));
        }else{
            teamList=teamDao.read("from Team where subdomain=:subdomain", new Params("subdomain",subdomain));
        }
        if(teamList!=null){
            return new ServiceResult<Team>(-4,null,"the subdomain is repeat");
        }
        Team team = new Team();
        team.setName(name);
        team.setDesc(desc);
        team.setIntro(intro);
        team.setSubdomain(subdomain);
        team.setStatus(1);
        team.setUidCreate(SessionHolder.get());
        team.setGmtCreate(System.currentTimeMillis() / 1000);
        team.setGmtModified(0L);
        team.setGmtBegin(gmtBegin.getTime() / 1000);
        team.setGmtEnd(gmtBegin.getTime() / 1000);
        if(id!=null){
            team.setId(id);
            teamDao.update(team);
        }else{
            teamDao.create(team);
        }
        return new ServiceResult<Team>(1,team);
    }
    
    public ServiceResult<Team> read(long id) {
        // TODO Auto-generated method stub
        Team team=teamDao.read(Team.class, id);
        return new ServiceResult<Team>(1,team);
    }


    public int count(long uidCreate, int pageSize) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("uidCreate", uidCreate);
        List<Team> teamList = teamDao.read("from Team where uidCreate=:uidCreate", param);
        int count = teamList.size();
        int totalpages = (count % pageSize == 0) ? (count / pageSize) : (count / pageSize + 1);
        return totalpages;
    }

    public TeamUserDao getTeamUserDao() {
        return teamUserDao;
    }

    public void setTeamUserDao(TeamUserDao teamUserDao) {
        this.teamUserDao = teamUserDao;
    }

    public TeamDao getTeamDao() {
        return teamDao;
    }

    public void setTeamDao(TeamDao teamDao) {
        this.teamDao = teamDao;
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

   

   
}
